const fs = require("fs");
const fsExtra = require("fs-extra");

const colors= require("colors");
// const { createCanvas, createImageData } = require("canvas");

const path = require("path");

const { TileSize, GrayscaleGeneration } = require("./mapHelper");

const {
  checkFolderExist,
  BilinearInterpolation,
  maxOrMin,
  CreateCanvas,
} = require("./utils");

const pow = Math.pow;

const TileCount = (level) => pow(2, level);

const TileMatrix = (level) => {
  return {
    xCount: TileCount(level) - 1,
    yCount: TileCount(level) - 1,
  };
};

const CreateDescriptionFile = async function (header, baseFilePath) {
  // const { app } = this;
  const writeJson = {
    xSize: header.nx,
    ySize: header.ny,
    xInterval: header.dx,
    yInterval: header.dy,
    pointCount: header.numberPoints,
    dataRange: [-header.lo1, header.la1, header.lo2, header.la2],
    categoryName: header.parameterCategoryName,
    startLevel: header.startLevel,
    endLevel: header.endLevel,
    unit: header.parameterUnit,
    min: header.min,
    max: header.max,
  };

  fs.writeFileSync(
    path.join(baseFilePath, "description.json"),
    JSON.stringify(writeJson, "", "\t")
  );

  console.log(`生成灰度图描述文件${colors.cyan(baseFilePath)}成功`);

  // (err) => {
  //     (err) => {
  //       if (err) {
  //         console.log(`生成灰度图描述文件失败,失败原因:${err}`);
  //         // app.logger.error(`生成灰度图描述文件失败,失败原因:${err}`);
  //       } else {
  //         // app.logger.info("生成灰度图描述文件成功");
  //       }
  //     };
  //   }
};

const CreateSlice = async function ({
  startLevel,
  endLevel,
  filePath,
  outputPath,
}) {
  try {
    fsExtra.readJson(filePath, function (err, json) {
      if (err) {
        console.error(err);
      }
      if (json.length) {
        // TODO:暂时为单要素单层数据
        const _json = json[0];
        const gridData = _json.data;
        const { nx, ny } = _json.header;
        const [min, max] = maxOrMin(gridData);

        for (let i = startLevel; i <= endLevel; i++) {
          const _tileMatrix = TileMatrix(i);
          const w = pow(2, i) * TileSize;
          const h = pow(2, i) * TileSize;

          console.time();
          let targetData = BilinearInterpolation(gridData, nx, ny - 1, w, h);
          console.timeEnd();

          const targetCanvas = GrayscaleGeneration(targetData, max, min, w, h);

          const zPath = path.join(outputPath, i + "");
          checkFolderExist(zPath, true);

          CreateDescriptionFile(
            Object.assign(
              _json.header,
              { startLevel, endLevel },
              { min: min, max: max }
            ),
            outputPath
          );

          for (let x = 0; x <= _tileMatrix.xCount; x++) {
            const xPath = path.join(zPath, x + "");
            checkFolderExist(xPath, true);

            for (let y = 0; y <= _tileMatrix.yCount; y++) {
              const yPath = path.join(xPath, y + ".png");
              const sx = x * TileSize;
              const sy = y * TileSize;
              const ctx = targetCanvas.getContext("2d");
              const sliceImageData = ctx.getImageData(
                sx,
                sy,
                TileSize,
                TileSize
              );

              const imgBuffer = CreateCanvas(
                sliceImageData,
                TileSize,
                TileSize
              );

              fs.writeFileSync(yPath, imgBuffer);

              console.log(`生成切片${colors.cyan(yPath)}成功`);

            }
          }
          
        }
        process.send("执行完成");
      } else {

        process.send("数据不存在");
      }
    });
  } catch (error) {

    process.send(error);
  }
};

process.on("message", function (params) {
  CreateSlice(params);
});

